<?php
class List_pegawai extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->helper('format');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');
		$this->load->model('guru_model');
		$this->load->model('master_model');
		$this->load->helper(array('form', 'url'));
		$this->load->library('upload');
	}
	
	function index()
	{
		//ver lib
		
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['NIP'] = array('NIP',100,TRUE,'center',0);
		$colModel['NAMA_LENGKAP'] = array('Nama Lengkap',150,TRUE,'center',1);
		$colModel['STATUS'] = array('Status',100,FALSE,'center',0);
		$colModel['ALAMAT_ASAL'] = array('Alamat Asal',260,TRUE,'center',1);
		$colModel['TELEPON'] = array('Telepon',80,TRUE,'center',1);
		$colModel['HP'] = array('HP',80,TRUE,'center',1);
		$colModel['EMAIL'] = array('Email',100,TRUE,'center',1);
		$colModel['ubah'] = array('Edit',50,FALSE,'center',0);
		$colModel['cetak'] = array('Cetak',50,FALSE,'center',0);
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '345',
		'rp' => 10,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Pegawai'
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		$buttons[] = array('Add','add','org_js');
		$buttons[] = array('Delete','delete','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Select All','add','org_js');
		$buttons[] = array('Deselect All','delete','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Cetak Daftar Pegawai','print','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Cetak Daftar Pegawai (Excel)','xls','org_js');
		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("/list_pegawai/listpegawai_grid/"),$colModel,'no','asc',$gridParams,$buttons);
		
		if($this->session->flashdata('suc_msg'))
			$data['header_info'] = '<div class="ret_success">'.$this->session->flashdata('suc_msg').'</div>';
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"<script type='text/javascript'>
			function org_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Add')
				{
					location.href='".base_url()."index.php/list_pegawai/input_pegawai/'; 
				}
				
				if (com=='Cetak Daftar Pegawai')
				{
					popup('".base_url()."index.php/list_pegawai/cetak_list_pegawai/html',1050,600);
				}
				
				if (com=='Cetak Daftar Pegawai (Excel)')
				{
					location.href='".base_url()."index.php/list_pegawai/cetak_list_pegawai/xls'; 
				}
				
				if (com=='Delete')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/list_pegawai/delete_pegawai')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			} 
			
			function popup(url,width,height) 
			{
				 var left   = (screen.width  - width)/2;
				 var top    = (screen.height - height)/2;
				 var params = 'width='+width+', height='+height;
				 params += ', top='+top+', left='+left;
				 params += ', directories=no';
				 params += ', location=no';
				 params += ', menubar=no';
				 params += ', resizable=no';
				 params += ', scrollbars=yes';
				 params += ', status=no';
				 params += ', toolbar=no';
				 newwin=window.open(url,'windowname5', params);
				 if (window.focus) {newwin.focus()}
				 return false;
			}
			</script>
			";	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
	}
	
	function listpegawai_grid()
	{
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		$valid_fields = array('NIP','NAMA_LENGKAP','ALAMAT_ASAL','TELEPON','HP','EMAIL');
		
		$this->flexigrid->validate_post('NIP','asc',$valid_fields);

		$records = $this->guru_model->get_pegawai();
		
		$this->output->set_header($this->config->item('json_header'));
		$no = 0;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{
			$gelard = ''; $gelarb = '';
			if($row->GELAR_DEPAN != '')
				$gelard = $row->GELAR_DEPAN.'. ';
			if($row->GELAR_BELAKANG != '')
				$gelarb = ', '.$row->GELAR_BELAKANG;
			$record_items[] = array($row->NIP,
			'<div align="center">'.$row->NIP .'</div>',
			'<div align="left">'.$gelard.$row->NAMA_LENGKAP .$gelarb .'</div>',
			'<div align="center">'.$row->NAMA_STATUS .'</div>',
			'<div align="left">'.$row->ALAMAT_ASAL .'</div>',
			'<div align="left">'.$row->TELEPON .'</div>',
			'<div align="left">'.$row->HP .'</div>',
			'<div align="left">'.$row->EMAIL .'</div>',
			'<a href=\''.site_url().'/list_pegawai/edit_pegawai/'.$row->NIP.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> ',
			'<a title="Cetak Detail Pegawai" href=\''.site_url().'/list_pegawai/cetak_list_pegawai/pdf/'.$row->NIP.'/\'><img border=\'0\' src=\''.base_url().'images/report/pdf.gif\'></a> '
			);
			$no++;
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
	
	function cek_validasi() {	
			// Setting Rules
			$this->form_validation->set_rules('nip', 'NIP', 'required|numeric|callback_validasi_nip');
			$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
			$this->form_validation->set_rules('tempat_lahir', 'Tempat Lahir', 'required');
			// $this->form_validation->set_rules('tanggal_lahir', 'Tanggal Lahir', 'required');
			$this->form_validation->set_rules('day', 'Tanggal Lahir', 'required|callback_validasi_date');
			$this->form_validation->set_rules('agama', 'Agama', 'required');
			$this->form_validation->set_rules('status', 'Status', 'required');
			$this->form_validation->set_rules('jenis_kelamin', 'Jenis Kelamin', 'required');
			$this->form_validation->set_rules('no_ktp', 'No KTP', 'numeric');
			$this->form_validation->set_rules('telepon', 'Telepon', 'numeric');
			$this->form_validation->set_rules('hp', 'Handphone', 'numeric');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}
	
	function validasi_nip(){
		$nip = $this->input->post('nip');
		
		$success = $this->guru_model->get_idguru($nip);
		
		if ($success == '0'){
		  return TRUE;
		}
		else{
		  $this->form_validation->set_message('validasi_nip', 'NIP sudah terdaftar.');
		  return FALSE;
		}
	}
	
	function validasi_date(){
		$day = $this->input->post('day');
		$month = $this->input->post('month');
		$year = $this->input->post('year');
		if (checkdate($month, $day, $year)){
		  return TRUE;
		}
		else{
		  $this->form_validation->set_message('validasi_date', 'Masukkan tanggal lahir yang benar.');
		  return FALSE;
		}
	}
	function input_pegawai()
    {
		if ($this->cek_validasi() == FALSE){
			$data['status'] = 'new';
			$data['agamaval'] = $this->input->post('agama');
			$data['statusval'] = $this->input->post('status');
			$data['yearval'] = $this->input->post('year');
			$data['monthval'] = $this->input->post('month');
			$data['dayval'] = $this->input->post('day');
			
			$data['agama'] = $this->guru_model->combo_agama();
			$data['status_guru'] = $this->guru_model->combo_status('pegawai');
			$data['content'] = $this->load->view('form_datapegawai',$data,true);
			$this->load->view('main',$data);
		}
		else{
			$this->insert_pegawai();
		}            
    }
	
	function insert_pegawai(){
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		$tgl_lahir = $this->input->post('year').'-'.$this->input->post('month').'-'.$this->input->post('day');
		$data = array(
			'NIP'				=> $this->input->post('nip'),
			'IS_AKADEMIK'		=> 0, // pegawai
			'STATUS'			=> $this->input->post('status'),
			'NAMA_LENGKAP'	 	=> $this->input->post('nama_lengkap'),
			'NAMA_PANGGILAN' 	=> $this->input->post('nama_panggilan'),
			'JENIS_KELAMIN'	 	=> $this->input->post('jenis_kelamin'),
			'GELAR_DEPAN'	 	=> $this->input->post('gelar_depan'),
			'GELAR_BELAKANG' 	=> $this->input->post('gelar_belakang'),
			'TEMPAT_LAHIR' 		=> $this->input->post('tempat_lahir'),
			// 'TANGGAL_LAHIR' 	=> xFormatDate2($this->input->post('tanggal_lahir')),
			'TANGGAL_LAHIR' 	=> $tgl_lahir,
			'AGAMA'			 	=> $this->input->post('agama'),
			'MENIKAH'		 	=> $this->input->post('menikah'),
			'NO_KTP'		 	=> $this->input->post('no_ktp'),
			'ALAMAT_ASAL'	 	=> $this->input->post('alamat_asal'),
			'ALAMAT_DOMISILI' 	=> $this->input->post('alamat_domisili'),
			'TELEPON' 			=> $this->input->post('telepon'),
			'HP' 				=> $this->input->post('hp'),
			'EMAIL' 			=> $this->input->post('email'),
			'KETERANGAN' 		=> $this->input->post('keterangan'),
			'ISAKTIF' 			=> 1
		);
		
		$ins_guru = $this->guru_model->insert_guru($data);
		
		if($ins_guru == true){
			if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = $this->input->post('nip');
				$config['upload_path'] = './uploads/pegawai/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				$config['max_size']	= '500';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['agama'] = $this->guru_model->combo_agama();
					$data['status_guru'] = $this->guru_model->combo_status('guru');
					$data['rs_guru'] = $this->guru_model->get_guruID($this->input->post('nip'));
					$data['content'] = $this->load->view('form_dataguru',$data,true);
					$this->load->view('main',$data);
				}
				else {	
						$data2 = array();
						$data2['FOTO'] = $this->input->post('nip').'.'.$filenamess;
						$this->guru_model->update_guru($data2,$this->input->post('nip'));
						
						$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
						redirect('list_pegawai');
					}				
			}else {	$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('list_pegawai');
				}
		}
		
	}
	
	function edit_pegawai($nip)
    {
 		if ($this->cek_validasi() == FALSE){
				$data['status'] = 'edit';
				$data['agama'] = $this->guru_model->combo_agama();
				$data['status_guru'] = $this->guru_model->combo_status('pegawai');
				$data['rs_pegawai'] = $this->guru_model->get_guruID($nip);
				$data['content'] = $this->load->view('form_datapegawai',$data,true);
				$this->load->view('main',$data);
			}
			else{
				$this->update_pegawai($nip);
			}            
    }
	
	function update_pegawai($nip){
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		
		$tgl_lahir = $this->input->post('year').'-'.$this->input->post('month').'-'.$this->input->post('day');
		$data = array(
			'NIP'				=> $this->input->post('nip'),
			'IS_AKADEMIK'		=> 0,
			'STATUS'			=> $this->input->post('status'),
			'NAMA_LENGKAP'	 	=> $this->input->post('nama_lengkap'),
			'NAMA_PANGGILAN' 	=> $this->input->post('nama_panggilan'),
			'JENIS_KELAMIN'	 	=> $this->input->post('jenis_kelamin'),
			'GELAR_DEPAN'	 	=> $this->input->post('gelar_depan'),
			'GELAR_BELAKANG' 	=> $this->input->post('gelar_belakang'),
			'TEMPAT_LAHIR' 		=> $this->input->post('tempat_lahir'),
			// 'TANGGAL_LAHIR' 	=> xFormatDate2($this->input->post('tanggal_lahir')),
			'TANGGAL_LAHIR' 	=> $tgl_lahir,
			'AGAMA'			 	=> $this->input->post('agama'),
			'MENIKAH'		 	=> $this->input->post('menikah'),
			'NO_KTP'		 	=> $this->input->post('no_ktp'),
			'ALAMAT_ASAL'	 	=> $this->input->post('alamat_asal'),
			'ALAMAT_DOMISILI' 	=> $this->input->post('alamat_domisili'),
			'TELEPON' 			=> $this->input->post('telepon'),
			'HP' 				=> $this->input->post('hp'),
			'EMAIL' 			=> $this->input->post('email'),
			'KETERANGAN' 		=> $this->input->post('keterangan'),
			'ISAKTIF' 			=> 1
		);
		// var_dump($_POST);exit;
		$this->guru_model->update_guru($data,$nip);
		
		if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = $this->input->post('nip');
				$config['upload_path'] = './uploads/pegawai/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				$config['max_size']	= '500';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				//delete files //
				if($this->input->post('fileold')!= ''){
					unlink('uploads/pegawai/'.$this->input->post('fileold'));
				}
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['agama'] = $this->guru_model->combo_agama();
					$data['status_guru'] = $this->guru_model->combo_status('guru');
					$data['rs_guru'] = $this->guru_model->get_guruID($nip);
					$data['content'] = $this->load->view('form_dataguru',$data,true);
					$this->load->view('main',$data);
				}
				else {	
						$data2 = array();
						$data2['FOTO'] = $this->input->post('nip').'.'.$filenamess;
						$this->guru_model->update_guru($data2,$nip);
						
						$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
						redirect('list_pegawai');
					}
			}
			else {	
					$this->session->set_flashdata('suc_msg', 'Data berhasil diupdate.');
					redirect('list_pegawai'); 
				}
	}
	
	//Delete
	function delete_pegawai()
	{
		$ta_ids_post_array = explode(",",$this->input->post('items'));
		$msg = '';
		foreach($ta_ids_post_array as $index => $ta_id){
			if (isset($ta_id) && $ta_id != "") {
				$this->guru_model->delete_guru($ta_id);
						
			
			$msg .= "Data Pegawai tersebut berhasil dihapus.\n";
			}
		}
		$this->output->set_header($this->config->item('ajax_header'));
		$this->output->set_output($msg);
	}
	
	function cetak_list_pegawai($type,$nip=''){
		if($nip=='' && $type =='xls'){
			$data['filename']="daftar_pegawai";
			$data['type'] = 'xls';
			$data['pegawai'] = $this->guru_model->get_pegawai_laporan();
			$this->load->view('cetak_daftar_pegawai',$data);
		}
		else if($nip=='' &&  $type =='html'){
			$data['filename']="daftar_pegawai";
			$data['type'] = 'html';
			$data['pegawai'] = $this->guru_model->get_pegawai_laporan();
			$this->load->view('cetak_daftar_pegawai_html',$data);
		}else{
			$this->load->helper('to_pdf');
			$this->load->helper('file');
			$filename="detail_pegawai_".$nip;
			$data['type'] = 'pdf';
			$data['pegawai'] = $this->guru_model->get_guruID($nip)->row();
			
			$html = $this->load->view('cetak_detail_pegawai',$data,TRUE);
			pdf_create($html, $filename);
		}

	}	
    
}
?>
